package com.lethe.medical.base.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




/**
 *  码拦截器
 * @author Lethe
 */
@WebFilter(filterName="EnCodingFilter",urlPatterns="/*",
        initParams={
                @WebInitParam(name="encoding", value="UTF-8"),
                @WebInitParam(name="contentType",value="Content-type"),
                @WebInitParam(name="contentValue",value="text/html;charset=UTF-8")
        })
public class EnCodingFilter implements Filter {

    /**
     * 编码
     */
    private String encoding;

    /**
     * 浏览器解析类型
     */
    private String contentType;

    /**
     * 浏览器解析类型值
     */
    private String contentValue;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        contentType = filterConfig.getInitParameter("contentType");
        contentValue = filterConfig.getInitParameter("contentValue");

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("EnCodingFilter执行了");
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setHeader(contentType, contentValue);
        response.setCharacterEncoding(encoding);

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
